﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using XXF.BaseService.ServiceCenter.Service.Provider;
using XXF.BaseService.ServiceCenter.SystemRuntime;

namespace XXF.BaseService.ServiceCenter.Service
{
    /// <summary>
    /// 服务发布帮助类
    /// 用于服务发布的一些版本兼容和简化
    /// </summary>
    public class ServicePublishHelper
    {
        protected static ServiceProvider service;

        /// <summary>
        /// 发布服务 (打开成功后,此方法会阻塞)
        /// </summary>
        /// <typeparam name="T">服务具体实现</typeparam>
        /// <param name="protocol">服务接口定义</param>
        /// <param name="opensuccesscallback">服务打开成功后的回调,无回调可传null</param>
        public static void Publish<T>(Type protocol, Action opensuccesscallback)
        {

            AppDomain.CurrentDomain.DomainUnload += CurrentDomain_DomainUnload;
            AppDomain.CurrentDomain.ProcessExit += CurrentDomain_ProcessExit;
            service = new ServiceProvider();
            service.RegisterProtocol(protocol);//注册服务的协议
            service.Run<T>(opensuccesscallback);//打开服务

        }

        static void CurrentDomain_ProcessExit(object sender, EventArgs e)
        {
            try
            { 
                LogHelper.Log(0, EnumLogType.Service, string.Format("当前域进程退出时释放完毕,服务器ip地址:{0}", CommonHelper.GetDefaultIP()));
            }
            catch (Exception exp)
            {
                LogHelper.Error(-1, EnumLogType.Service, string.Format("当前域进程退出时释放出错,服务器ip地址:{0}", CommonHelper.GetDefaultIP()), exp);
                throw exp;
            }
        }
        static void CurrentDomain_DomainUnload(object sender, EventArgs e)
        {
            try
            {
                if (null != service)
                {
                    service.Dispose();
                }
                LogHelper.Log(0, EnumLogType.Service, string.Format("当前域域卸载时释放完毕,服务器ip地址:{0}", CommonHelper.GetDefaultIP()));
            }
            catch (Exception exp)
            {
                LogHelper.Error(0, EnumLogType.Service, string.Format("当前域域卸载释放出错,服务器ip地址:{0}", CommonHelper.GetDefaultIP()), exp);
                throw exp;
            }
        }
    }
}
